<template>
    <el-form
        :inline="true"
        ref="searchFormRef"
        style="max-width: 100%"
        label-width="auto"
        :model="queryConditions"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="业务部门" prop="businessDepartment">
            <el-input
                v-model="queryConditions.businessDepartment"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
            <el-select
                v-model="queryConditions.customerId"
                style="width: 200px"
                size="large"
                placeholder="请选择"
                clearable
            >
                <el-option
                    v-for="customer in customerList"
                    :key="customer.id"
                    :label="customer.name"
                    :value="customer.id"
                />
            </el-select>
        </el-form-item>
        <el-button type="primary" :icon="Search" @click="search">查询</el-button>
        <el-button type="primary" :icon="RefreshRight" @click="resetForm">重置</el-button>
    </el-form>
    <SalesOrderExecutionStatusLimitPage
        :table-data="formattedTableData"
        :columns="tableColumns"
        :current-page="pageNo"
        :total="allPage"
        :page-size="pageSize"
        @page-change="handlePageChange"
        @action="handleTableAction"
        @edit="handleEditAction"
        @delete="handleDeleteAction"
    />
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { Search, RefreshRight } from '@element-plus/icons-vue';
import { ref, computed, reactive, nextTick } from 'vue';
import { ElMessageBox, ElMessage, type FormInstance, ElLoading } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';
import SalesOrderExecutionStatusLimitPage from "@/salesOrderExecutionStatus/SalesOrderExecutionStatusLimitPage.vue";

let pageNo = ref(1);
let pageSize = ref(5);
let allPage = ref(0);
let router = useRouter();
const searchFormRef = ref<FormInstance>();

// 查询
const search = () => {
    pageNo.value = 1; // 重置到第一页
    fetchData(1);
};

// 重置表单
const resetForm = () => {
    if (!searchFormRef.value) return;
    nextTick(() => {
        searchFormRef.value!.resetFields();
        pageNo.value = 1;
        fetchData(1);
    });
};

// 查询条件
const queryConditions = reactive({
    businessDepartment: '',
    customerId: null
});

let tableData = ref<any[]>([]);

// 格式化表格数据
const formattedTableData = computed(() => {
    return tableData.value.map((item, index) => ({
        ...item,
        index: (pageNo.value - 1) * pageSize.value + index + 1,
        executionFinished: formatExecutionFinished(item.executionFinished)
    }));
});

const formatExecutionFinished = (executionFinished: number | string) => {
    const state = Number(executionFinished);  // 确保是数字
    switch (state) {
        case 0:
            return '否';
        case 1:
            return '是';
        default:
            return '未知状态';
    }
};

const tableColumns = ref([
    { prop: 'index', label: '序号' },
    { prop: 'name', label: '客户' }, // 客户名称来自 public_customer 表
    { prop: 'businessDepartment', label: '业务部门' },
    { prop: 'salesPerson', label: '业务员' },
    { prop: 'code', label: '单据编号' },
    { prop: 'codeDate', label: '单据日期' },
    { prop: 'salesQuantity', label: '销售数量' },
    { prop: 'salesAmount', label: '销售金额' },
    { prop: 'outboundQuantity', label: '出库数量' },
    { prop: 'outboundAmount', label: '出库金额' },
    { prop: 'settlementQuantity', label: '结算数量' },
    { prop: 'settlementAmount', label: '结算金额' },
    { prop: 'invoicedAmount', label: '已开票金额' },
    { prop: 'executionFinished', label: '是否执行' }
]);

const handlePageChange = (newPage: number) => {
    pageNo.value = newPage;
    fetchData(newPage);
};

// 导出销售订单执行情况数据
const handleExport = async () => {
    const params = {
        pageNo: pageNo.value,
        pageSize: pageSize.value,
        businessDepartment: queryConditions.businessDepartment,
        customerId: queryConditions.customerId
    };
    const loading = ElLoading.service({ text: "正在导出..." });
    try {
        const response = await axios.post("http://localhost:8085/salesOrderExecutionStatus/export", params, {
            responseType: "blob"
        });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "销售订单执行情况表.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success("导出成功");
    } catch (error) {
        console.error("导出失败:", error);
        ElMessage.error("导出失败，请稍后重试");
    } finally {
        loading.close();
    }
};

const handleTableAction = (actionName: string) => {
    console.log('触发操作:', actionName);
    if (actionName === 'add') {
        router.push('/home/fp/addXSFP');
    }
    if (actionName === 'export') {
        handleExport(); // 触发导出
    }
};

const handleEditAction = (row: any) => {
    if (row.code) {
        router.push({
            name: 'UpdateSalesInvoice',
            params: { code: row.code }
        });
    } else {
        ElMessage.error('单据编号不存在，无法跳转到修改页面');
    }
};

const handleDeleteAction = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定删除此记录？此操作不可恢复。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await axios.post(`http://localhost:8085/salesOrderExecutionStatus/delete?id=${row.id}`);
        ElMessage.success('删除成功');
        await fetchData(pageNo.value); // 刷新
    } catch (error) {
        ElMessage.error('删除失败，请稍后重试');
    }
};

async function fetchData(page: number) {
    try {
        console.log(queryConditions.businessDepartment, ",", queryConditions.customerId);
        let response = await axios.post('http://localhost:8085/salesOrderExecutionStatus/selectByPage', {
            pageNo: page,
            pageSize: pageSize.value,
            businessDepartment: queryConditions.businessDepartment,
            customerId: queryConditions.customerId
        });
        tableData.value = response.data.data.list;
        allPage.value = response.data.data.total;
        console.log(tableData.value);
    } catch (error) {
        ElMessage.error('获取订单执行情况失败');
        tableData.value = [];
        allPage.value = 0;
    }
}

// 存储所有客户
const customerList = ref<any[]>([]);
const fetchAllCustomers = async () => {
    try {
        const res = await axios.post('http://localhost:8083/Customer/selectAllCustomer');
        customerList.value = res.data.data;
    } catch (e) {
        ElMessage.error('获取客户数据失败');
        console.error('Error fetching customers:', e);
        customerList.value = [];
    }
};

onMounted(() => {
    fetchData(1);
    fetchAllCustomers();
});
</script>

<style scoped>
</style>
